package com.toocms.jinjuhang.ui.mine.management_system.vip_center

import android.app.Application
import android.os.Bundle
import android.text.TextUtils
import androidx.databinding.ObservableArrayList
import androidx.databinding.ObservableField
import com.blankj.utilcode.util.ActivityUtils
import com.blankj.utilcode.util.ResourceUtils
import com.blankj.utilcode.util.StringUtils
import com.toocms.jinjuhang.BR
import com.toocms.jinjuhang.R
import com.toocms.jinjuhang.config.Constants
import com.toocms.jinjuhang.config.Urls
import com.toocms.jinjuhang.config.UserRepository
import com.toocms.jinjuhang.data.center.CommissionerData
import com.toocms.jinjuhang.widget.view_model.requestData
import com.toocms.tab.base.BaseModel
import com.toocms.tab.base.BaseViewModel
import com.toocms.tab.binding.ItemBinding
import com.toocms.tab.binding.command.BindingAction
import com.toocms.tab.binding.command.BindingCommand
import com.toocms.tab.bus.event.SingleLiveEvent
import com.toocms.tab.widget.picker.builder.TimePickerBuilder
import java.text.SimpleDateFormat
import java.util.*

class ServiceSpecialistModel(application: Application, val bundle: Bundle?) :
    BaseViewModel<BaseModel>(application) {

    val dataFormat = SimpleDateFormat("yyyy-MM-dd")
    val calendar = Calendar.getInstance()
    var p = 1
    val defaultSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_bottom_gray)
    }
    val upSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_blue_bottom_gray)
    }
    val downSortIconDrawable by lazy {
        ResourceUtils.getDrawable(R.mipmap.icon_arrow_top_gray_bottom_blue)
    }
    var keywords: String? = null
        set(value) {
            field = value
            refresh()
        }
    val organizationId by lazy {
        bundle?.getString(Constants.BundleKey.KEY_ORGANIZATION_ID) ?: ""
    }

    val startTimeObservableField by lazy {
//        ObservableField(dataFormat.format(calendar.time))
        ObservableField<String>()
    }
    val endTimeObservableField by lazy {
//        ObservableField(dataFormat.format(calendar.time))
        ObservableField<String>()
    }
    val sortObservableField = ObservableField<ServiceSpecialistSortType>()
    val subsidiesAmountIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val popularizeNumberIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val groupTotalIntegralIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val orderSumIconObservableField by lazy {
        ObservableField(defaultSortIconDrawable)
    }
    val subsidiesAmountClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            ServiceSpecialistSortType.SUBSIDY_SUM_UP -> sortObservableField.set(
                ServiceSpecialistSortType.SUBSIDY_SUM_DOWN
            )
            ServiceSpecialistSortType.SUBSIDY_SUM_DOWN -> sortObservableField.set(
                ServiceSpecialistSortType.SUBSIDY_SUM_UP
            )
            else -> sortObservableField.set(ServiceSpecialistSortType.SUBSIDY_SUM_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val popularizeNumberClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            ServiceSpecialistSortType.POPULARIZE_NUMBER_UP -> sortObservableField.set(
                ServiceSpecialistSortType.POPULARIZE_NUMBER_DOWN
            )
            ServiceSpecialistSortType.POPULARIZE_NUMBER_DOWN -> sortObservableField.set(
                ServiceSpecialistSortType.POPULARIZE_NUMBER_UP
            )
            else -> sortObservableField.set(ServiceSpecialistSortType.POPULARIZE_NUMBER_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val groupTotalIntegralClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_UP -> sortObservableField.set(
                ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_DOWN
            )
            ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_DOWN -> sortObservableField.set(
                ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_UP
            )
            else -> sortObservableField.set(ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val orderSumClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        when (sortObservableField.get()) {
            ServiceSpecialistSortType.ORDER_SUM_UP -> sortObservableField.set(
                ServiceSpecialistSortType.ORDER_SUM_DOWN
            )
            ServiceSpecialistSortType.ORDER_SUM_DOWN -> sortObservableField.set(
                ServiceSpecialistSortType.ORDER_SUM_UP
            )
            else -> sortObservableField.set(ServiceSpecialistSortType.ORDER_SUM_DOWN)
        }
        refreshIcon()
        refresh()
    })
    val startTimeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(1)
    })
    val endTimeClickBindingCommand = BindingCommand<BindingAction>(BindingAction {
        selectedTime(2)
    })


    val stopRefreshOrLoadSingleLiveEvent = SingleLiveEvent<Unit>()

    val refreshBindingCommand = BindingCommand<BindingAction>(BindingAction {
        refresh()
    })

    val loadBindingCommand = BindingCommand<BindingAction>(BindingAction {
        load()
    })


    val items = ObservableArrayList<ServiceSpecialistItemModel>()
    val itemBinding = ItemBinding.of<ServiceSpecialistItemModel>(
        BR.serviceSpecialistItemModel,
        R.layout.item_service_specialist
    )

    init {
        refresh(false)
    }


    /**
     * 选择时间
     *
     * @param type 1(开始时间),2(结束时间)
     */
    private fun selectedTime(type: Int) {
        TimePickerBuilder(
            ActivityUtils.getTopActivity()
        ) { date, v ->
            when (type) {
                1 -> {
                    startTimeObservableField.set(dataFormat.format(date))
                }
                2 -> {
                    endTimeObservableField.set(dataFormat.format(date))
                }
            }
            refresh()
        }.run {
            setTitleText(
                "${StringUtils.getString(if (1 == type) R.string.str_start else R.string.str_end)}${
                    StringUtils.getString(
                        R.string.str_date
                    )
                }"
            )
            setDividerColor(0x00000000)
            setLabel("", "", "", "", "", "")
            val startDate = startTimeObservableField.get()
            val endDate = endTimeObservableField.get()
            when (type) {
                1 -> {
                    if (!TextUtils.isEmpty(startDate)) {
                        calendar.time = dataFormat.parse(startDate)
                    }
                }
                2 -> {
                    if (!TextUtils.isEmpty(endDate)) {
                        calendar.time = dataFormat.parse(endDate)
                    }
                }
            }
            setDate(calendar)
            build()
        }.show()
    }

    private fun refreshIcon() {
        subsidiesAmountIconObservableField.set(defaultSortIconDrawable)
        popularizeNumberIconObservableField.set(defaultSortIconDrawable)
        groupTotalIntegralIconObservableField.set(defaultSortIconDrawable)
        orderSumIconObservableField.set(defaultSortIconDrawable)
        when (sortObservableField.get()) {
            ServiceSpecialistSortType.SUBSIDY_SUM_DOWN -> subsidiesAmountIconObservableField.set(
                downSortIconDrawable
            )
            ServiceSpecialistSortType.SUBSIDY_SUM_UP -> subsidiesAmountIconObservableField.set(
                upSortIconDrawable
            )
            ServiceSpecialistSortType.POPULARIZE_NUMBER_DOWN -> popularizeNumberIconObservableField.set(
                downSortIconDrawable
            )
            ServiceSpecialistSortType.POPULARIZE_NUMBER_UP -> popularizeNumberIconObservableField.set(
                upSortIconDrawable
            )
            ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_DOWN -> groupTotalIntegralIconObservableField.set(
                downSortIconDrawable
            )
            ServiceSpecialistSortType.GROUP_TOTAL_INTEGRAL_UP -> groupTotalIntegralIconObservableField.set(
                upSortIconDrawable
            )
            ServiceSpecialistSortType.ORDER_SUM_DOWN -> orderSumIconObservableField.set(
                downSortIconDrawable
            )
            ServiceSpecialistSortType.ORDER_SUM_UP -> orderSumIconObservableField.set(
                upSortIconDrawable
            )
            else -> {}
        }
    }

    private fun refresh(isShowLoading: Boolean = false) {
        p = 1
        requestData(p, isShowLoading)
    }

    private fun load() {
        p++
        requestData(p)
    }

    private fun requestData(p: Int, isShowLoading: Boolean = false) {
        val params = mutableMapOf<String, String?>()
        params["member_id"] = UserRepository.user.member_id
        params["organization_id"] = organizationId
        params["keywords"] = keywords
        params["start_time"] = startTimeObservableField.get()
        params["end_time"] = endTimeObservableField.get()
        params["sort"] = sortObservableField.get()?.code ?: ""
        params["p"] = p.toString()
        requestData(
            Urls.Center.COMMISSIONER,
            params,
            resultClass = CommissionerData::class.java,
            isShowLoading = isShowLoading,
            result = {
                if (1 == p) items.clear()
                it.list?.forEach {
                    items += ServiceSpecialistItemModel(this, ObservableField(it))
                }
            },
        finish = {
            stopRefreshOrLoadSingleLiveEvent.call()
        })
    }

}